import 'dart:io';

import 'package:excel_utils/del_blank_rows_page.dart';
import 'package:excel_utils/pages/month_report/bloc/month_data_merging_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class MonthDataMergingPage extends StatefulWidget {
  const MonthDataMergingPage({super.key});

  @override
  State<MonthDataMergingPage> createState() => _MonthDataMergingPageState();
}

class _MonthDataMergingPageState extends State<MonthDataMergingPage> {
  File? childFile;
  File? mainFile;
  List<File> childFiles = [];
  String sheetName = "Attend Modifier Result、CMS、Sheet2";
  String mainSheetName = "Main";
  String resultMsg = "";
  double margeProgress = 0.0;
  bool isMergeLoading = false;
  bool isExtractLoading = false;
  List<List<dynamic>> originData = [];
  StringBuffer analysisRes = StringBuffer();

  MonthDataMergingBloc? monthDataMergingBloc;

  showSnackBar(Text msg) {
    ScaffoldMessenger.of(context)..hideCurrentSnackBar()..showSnackBar(SnackBar(content: msg));
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<MonthDataMergingBloc>(
      create: (BuildContext context) {
        monthDataMergingBloc = MonthDataMergingBloc();
        return monthDataMergingBloc!;
      },
      child: BlocConsumer<MonthDataMergingBloc, MonthDataMergingState>(
        builder: (BuildContext context, MonthDataMergingState state) {
          if (state is MonthDataMergingSelectChildDataState) {
            childFiles = state.childFiles;
          } else if (state is MonthDataMergingChildFilesClearState) {
            childFiles.clear();
            originData.clear();
            analysisRes.clear();
          } else if (state is MonthDataMergingRemoveChildFileState) {
            childFiles.removeAt(state.index);
          } else if (state is MonthExtractChildFileLoadingState) {
            isExtractLoading = true;
            analysisRes.clear();
          } else if (state is MonthExtractChildFileSuccessState) {
            isExtractLoading = false;
            originData.clear();
            originData = state.originDataTemp;
          } else if (state is MonthExtractChildFileFailureState) {
            isExtractLoading = false;
          } else if (state is MonthExtractChildFileProcessState) {
            analysisRes.write("${state.msg}\n");
          } else if (state is MonthDataMergingSelectMainDataState) {
            mainFile = state.mainFile;
          } else if (state is MonthMergingXlsxDataProgressState) {
            isMergeLoading = true;
            resultMsg = state.resultMsg;
            margeProgress = state.margeProgress;
          } else if (state is MonthExtractMainFileSuccessState) {
            isMergeLoading = false;
            resultMsg = state.msg;
          } else if (state is MonthExtractMainFileFailureState) {
            isMergeLoading = false;
            resultMsg = state.msg;
          } else if (state is MonthDataMergingResetMainDataState) {
            mainFile = null;
          }
          return buildUI();
        },
        listener: (BuildContext context, MonthDataMergingState state) {
          if (state is MonthDataMergingOpenFileState) {
            String? clickFile = state.file?.path.toString();
            showSnackBar(Text("正在打开文件$clickFile", style: TextStyle(color: Colors.blue)));
          } else if (state is MonthDataMergingRemoveChildFileState) {
            showSnackBar(Text("删除成功${state.childFile.path}", style: TextStyle(color: Colors.green)));
          } else if (state is MonthExtractChildFileSuccessState) {
            showSnackBar(Text("解析成功", style: TextStyle(color: Colors.green)));
          } else if (state is MonthExtractChildFileFailureState) {
            showSnackBar(Text("解析失败：${state.msg}", style: TextStyle(color: Colors.red)));
          } else if (state is MonthExtractMainFileSuccessState) {
            showSnackBar(Text("合并成功：${state.msg}", style: TextStyle(color: Colors.green)));
          } else if (state is MonthExtractMainFileFailureState) {
            showSnackBar(Text("合并失败：${state.msg}", style: TextStyle(color: Colors.red)));
          }
        },
      ),
    );
  }

  Widget buildUI() {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Row(
          children: [
            Expanded(
                child: Column(children: [
              const SizedBox(height: 20),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20),
                child: TextField(
                  onChanged: (value) {
                    sheetName = value;
                  },
                  decoration: const InputDecoration(
                    hintText: "文件中Sheet的名称，默认为CMS，如果有不同的名称，使用、分割",
                    border: OutlineInputBorder(),
                    labelText: '文件中Sheet的名称，默认为CMS，如果有不同的名称，使用、分割',
                  ),
                ),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  monthDataMergingBloc?.add(MonthSelectChildFileEvent(
                    childFiles: childFiles,
                  ));
                },
                child: const Text('1 选择需要合并的文件'),
              ),
              if (childFile != null) Text("当前的文件数量：${childFiles.length}"),
              Container(
                width: 500,
                height: 300,
                margin: const EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(10)),
                  border: Border.all(color: Colors.grey, width: 1),
                ),
                child: ListView.separated(
                  padding: const EdgeInsets.all(10),
                  itemBuilder: (BuildContext context, int index) {
                    File file = childFiles[index];
                    return Row(
                      children: [
                        Expanded(child: Text(file.path)),
                        IconButton(
                            onPressed: () {
                              monthDataMergingBloc?.add(MonthOpenChildFileEvent(file: file));
                            },
                            icon: const Icon(Icons.folder_open_sharp, color: Colors.blue)),
                        IconButton(
                            onPressed: () {
                              monthDataMergingBloc?.add(MonthRemoveChildFileEvent(index: index, file: file));
                            },
                            icon: const Icon(Icons.remove_circle_outline, color: Colors.red))
                      ],
                    );
                  },
                  itemCount: childFiles.length,
                  separatorBuilder: (BuildContext context, int index) {
                    return const Padding(padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Divider(height: 1, color: Colors.grey));
                  },
                ),
              ),
              if (childFiles.isNotEmpty)
                ElevatedButton(
                  onPressed: () async {
                    monthDataMergingBloc?.add(const MonthClearChildFileEvent());
                  },
                  child: const Text('清空已经选择的文件'),
                ),
              const SizedBox(height: 20),
              ElevatedButton(
                  onPressed: () {
                    monthDataMergingBloc?.add(MonthExtractChildFileEvent(childFiles: childFiles, sheetName: sheetName));
                  },
                  child: Text("2 解析选择中的数据${originData.length}")),
              const SizedBox(height: 20),
              if (isExtractLoading) const CircularProgressIndicator(),
              const SizedBox(height: 20),
              Visibility(
                  visible: false,
                  child: ElevatedButton(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const DelBlankRowsPage(),
                          ),
                        );
                      },
                      child: const Text("del blanks rows"))),
              if (analysisRes.isNotEmpty)
                Expanded(
                    child: SingleChildScrollView(
                  child: Text(analysisRes.toString()),
                )),
            ])),
            Expanded(
                child: Column(children: [
              const SizedBox(height: 20),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 20),
                child: TextField(
                  onChanged: (value) {
                    mainSheetName = value;
                  },
                  decoration: const InputDecoration(hintText: "文件中Sheet的名称，默认为Main", border: OutlineInputBorder(), labelText: '文件中Sheet的名称，默认为Main'),
                ),
              ),
              const SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      monthDataMergingBloc?.add(const MonthSelectMainFileEvent());
                    },
                    child: const Text(
                      '3 选择主文件',
                    ),
                  ),
                  const SizedBox(
                    width: 20,
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      monthDataMergingBloc?.add(MonthMainFileResetEvent());
                    },
                    child: const Text(
                      '重置',
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 50),
              if (isMergeLoading)
                Column(
                  children: [
                    LinearProgressIndicator(
                      value: margeProgress,
                      minHeight: 10,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    Text(
                      resultMsg,
                    ),
                  ],
                ),
              if (mainFile != null)
                Column(
                  children: [
                    Text(
                      "${mainFile?.path}",
                    ),
                  ],
                ),
              ElevatedButton(
                onPressed: () async {
                  monthDataMergingBloc
                      ?.add(MonthMergingXlsxDataLoadingEvent(isMergeLoading: isMergeLoading, mainFile: mainFile, originData: originData, mainSheetName: mainSheetName, isNullHeader: false));
                },
                child: const Text(
                  '4 开始合并',
                ),
              ),
              const SizedBox(height: 50),
              Expanded(
                  child: SingleChildScrollView(
                child: Column(
                  children: [
                    const Text.rich(TextSpan(
                      children: [
                        TextSpan(text: "准备工作\n"),
                        TextSpan(text: "1.提前准备好需要合并的文件，确保文件格式正确，且文件中包含需要合并的Sheet，软件内置默认是 Attend Modifier Result、CMS\n", style: TextStyle(color: Colors.blue)),
                        TextSpan(text: "2.选择需要合并的文件，点击解析按钮，解析数据，如果操作了删除单个文件，需要重新解析数据\n"),
                        TextSpan(text: "3.主文件中写入的是Main Sheet，如果没有，请先创建Main Sheet，需要把表头的前三行先弄好\n", style: TextStyle(color: Colors.red)),
                        TextSpan(text: "4.选择主文件，点击开始合并按钮，开始合并数据\n"),
                        TextSpan(text: "5.尽量操作一次合并，避免重复操作，如果需要重复操作，请先清空主文件中的数据，保留前三行的表头\n", style: TextStyle(color: Colors.deepPurple)),
                      ],
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 20,
                      ),
                    )),
                    SizedBox(
                      height: 100,
                      child: Image.asset("assets/images/main_sheet.png", fit: BoxFit.fill),
                    ),
                  ],
                ),
              ))
            ])),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: const BackButton(),
        ));
  }
}
